<template>
    <div>
        <!-- <div class="container"> -->
            
        <el-row >
            <el-col :span="10">
                <el-button :icon="ArrowLeftBold" @click="prev" />
               <el-button :icon="ArrowRightBold" @click="next" />
           </el-col>
            <el-col :span="4" class="fc-center">
                <p class="title"> {{ title }}</p>
            </el-col>
             <el-col :span="10">
                    <el-button-group style="float: right;">
                        <el-button @click="month"> 月 </el-button>
                        <el-button @click="week"> 周 </el-button>
                        <el-button @click="today"> 今天 </el-button>
                    </el-button-group>
                </el-col>
        </el-row>
        <el-divider></el-divider>
        <div v-if="showFullcalendar">加载数据中......</div>
        <FullCalendar v-else id="calendar" ref="fullCalendar"  :options="calendarOptions">
            <template v-slot:eventContent="arg">
                <el-popover placement="top-start" :width="200" trigger="click">
                    <template #reference>
                        <i class="title">{{ arg.event.title }}</i>
                    </template>
                    <div class="popper-content">
                        <span>{{ arg.timeText }}</span>
                        <i>{{ arg.event.title }}</i>
                    </div>
                </el-popover>
            </template>
            <template v-slot:dayCellContent="arg">
                {{ arg.dayNumberText }}
            </template>
            <template v-slot:resourceLabelContent="arg">
                {{ arg.resource.id }}
            </template>
        </FullCalendar>

        <!-- </div> -->
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, watch, nextTick } from 'vue'
import { ArrowRightBold, ArrowLeftBold } from '@element-plus/icons-vue'
import FullCalendar from "@fullcalendar/vue3";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import listPlugin from "@fullcalendar/list";
import interactionPlugin from "@fullcalendar/interaction";
import resourceTimelinePlugin from "@fullcalendar/resource-timeline";

import {getCourseScheduleList}  from '@/api/course'

const props = defineProps(['isDetail','courseId'])
const emit = defineEmits(['update:isDetail','update:courseId'])
let clickCount = 0;
let prevDom = ""
const showFullcalendar = ref(true)
let title = ref('')

const type = ref("dategrid")
const calendarOptions = reactive({
    locale: "zh",
    timeZone: "UTC",
    plugins: [
        dayGridPlugin,
        timeGridPlugin,
        listPlugin,
        resourceTimelinePlugin,
        interactionPlugin,
    ],
    buttonText: {
        // 设置按钮
        today: "今天",
        month: "月",
        week: "周",
        dayGrid: "天",
    },
    initialView: "dayGridMonth", // 设置默认显示月，可选周、日
    resourceOrder: "number",     
    editable: true,
    dayMaxEvents: true, // allow "more" link when too many events
    eventDurationEditable: true, // 可以调整事件的时间
    selectable: true, // 日历格子可选择
    nowIndicator: true, // 现在的时间线显示
    eventDisplay: "block", // 争对全天的情况下，以块状显示
    headerToolbar: false, // 隐藏头部的导航栏
    selectMirror: false,
    displayEventEnd: true, // like 08:00 - 13:00
    eventTimeFormat: {
        // like '14:30:00'
        hour: "2-digit",
        minute: "2-digit",
        meridiem: false,
        hour12: false, // 设置时间为24小时
    },
    events: [],
    eventColor: "#378006",
    allDayText: "全天",
    dateClick: handleDateClick, //点击日程事件
    eventClick: handleEventClick,  //点击日历中的某一日程
    select: handleDateSelect, // 监听用户选择的时间段，
    eventDrop: handleEventDrop,  //监听事件被拖动的操作
    eventResize: handleEventResize, //监听事件调整大小的操作
    schedulerLicenseKey: "GPL-My-Project-Is-Open-Source",
    views: {
        customTimeLineWeek: {
            type: "resourceTimeline",
            duration: { weeks: 1 },
            slotDuration: { days: 1 },
            buttonText: "Custom Week",
            slotLabelFormat: {
                weekday: "long",
                // month: 'numeric',
                // day: 'numeric',
                omitCommas: true,
            },
        },
        customTimeLineMonth: {
            type: "resourceTimeline",
            duration: { month: 1 },
            slotLabelFormat: {
                // month: 'numeric',
                day: "numeric",
                // omitCommas: true,
            },
        },
        customGridWeek: {
            type: "timeGridWeek",
            dayHeaderFormat: {
                weekday: "long",
            },
            slotLabelFormat: {
                // 左侧时间格式
                hour: "2-digit",
                minute: "2-digit",
                meridiem: "lowercase",
                hour12: false, // false设置时间为24小时
            },
        },
    },
    // 切换视图调用的方法
    datesSet() { },

})

const calendarApi = ref()
const monthEvent = ref([ ])
//todo  调用后端接口进行数据展示  实际开发中  数据可以通过父传递给子组件  父组件在添加 复制排课之后 数据要重新请求
getCourseScheduleList().then(res=>{
      console.log(res,'排课计划')
      monthEvent.value= res.data
})
// const weekEvent = ref([
//     {
//         id: "4",
//         resourceId: "4",
//         title: "周待办",
//         start: "2024-07-11",
//         color: "red",
//     },
//     {
//         id: "5",
//         resourceId: "5",
//         title: "待办1",
//         start: "2024-07-04 10:00",
//         end: "2024-07-04 18:00",
//         color: "orange",
//     },
// ])
const dayDate = ref('')
const dialogFormVisible = ref(false)
const form = reactive({ content: '' })
const selectInfo1 = ref({ startStr: new Date(), endStr: new Date() })
const fullCalendar = ref()
onMounted(async() => {
    setTimeout(async() => {
        showFullcalendar.value = false;
       await nextTick(() => {
        // console.log('11111',fullCalendar.value)
         if(fullCalendar.value){ 
            calendarApi.value = fullCalendar.value.getApi()
            title.value = calendarApi.value.view.title
            console.group('%c%s', 'color:blue', `${new Date().getTime()} 数据----------`)
            console.log('数据fullCalendar', fullCalendar.value.getApi())
            console.log('数据calendarApi', calendarApi.value)
            console.groupEnd()
            // calendarOptions.events = calendarApi.value.view.type === "dayGridMonth" ? monthEvent.value : weekEvent.value;
            getDtata();
        }

        });
    }, 100);

})




function getDtata() {
    // setTimeout(() => {
        calendarOptions.events = calendarApi.value.view.type === "dayGridMonth" ? monthEvent.value : weekEvent.value
        //  console.log(calendarOptions.events)
    // }, 20)

}

//点击日历中的某一日程
function handleEventClick(clickInfo) {
    console.log('clickInfo:', clickInfo);
    // 用户点击事件时触发，用于编辑或删除事件
    const event = clickInfo.event;
    emit("update:isDetail", false)
    emit("update:courseId", event.id)
    console.log('点击某一日程:', event.title,event.id,event.start);
    // 这里可以弹出模态框进行编辑或调用删除函数等操作
}
// 单击事件(日历中的某一天)
function handleDateClick(e) {
    dayDate.value = e.dateStr;
    if (e.dateStr !== prevDom) {
        clickCount = 0;
    }
    clickCount += 1;
    prevDom = e.dateStr;
    setTimeout(() => {
        if (clickCount === 2) {
            console.log("db click");
        } else if (clickCount === 1) {
            console.log("one click");
        }
        clickCount = 0;
    }, 300);
}


// 监听用户选择的时间段，当用户选择了一段时间后会触发该回调，可以在这里处理创建新的日程。
function handleDateSelect(selectInfo) {
    console.log('selectInfo3: ', selectInfo);
    selectInfo1.value = selectInfo;
    form.content = '';
  
    // 用户选择了一个日期范围时触发
    dialogFormVisible.value = true;
}
// 用户拖动移动事件时触发
function handleEventDrop(dropInfo) {
    console.log('dropInfo: ', dropInfo);
    const updatedEvent = { ...dropInfo.event };
    updatedEvent.start = dropInfo.revertDuration ? dropInfo.oldEvent.start : dropInfo.event.start;
    updatedEvent.end = dropInfo.event.end;

    // 更新服务器上的事件或者重新排序你的事件数组
    // 示例：updateEventOnServer(updatedEvent);

    // 如果是在内存中维护事件，则更新本地数据
    const index = calendarOptions.events.findIndex(e => e.id === updatedEvent.id);
    if (index !== -1) {
        calendarOptions.events.splice(index, 1, updatedEvent);
    }
}
// 用户调整事件长度时触发
function handleEventResize(resizeInfo) {
    console.log('resizeInfo: ', resizeInfo);
    const updatedEvent = { ...resizeInfo.event };
    updatedEvent.end = resizeInfo.event.end;

    // 同样更新服务器或本地数据
    // 示例：updateEventOnServer(updatedEvent);

    const index = calendarOptions.events.findIndex(e => e.id === updatedEvent.id);
    if (index !== -1) {
        calendarOptions.events.splice(index, 1, updatedEvent);
    }
}


//点击更多
function more(e) {
    console.log('more ', e)
}
// 切换
function prev() {
    calendarApi.value.prev();
    title.value = calendarApi.value.view.title;
}
function next() {
    calendarApi.value.next();
    title.value = calendarApi.value.view.title;
}
// 今天
function today(date, jsEvent, view) {
    calendarApi.value.today();
    title.value = calendarApi.value.view.title;
    calendarApi.value.changeView("timeGridDay");

}
// 月
function month() {
    console.log('month')
    if (type.value === "timeline") {
        calendarApi.value.changeView("customTimeLineMonth");
    } else {
        calendarApi.value.changeView("dayGridMonth");
    }
    calendarApi.value.today();
    title.value = calendarApi.value.view.title;
}
// 周
function week() {
    if (type === "timeline") {
        calendarApi.value.changeView("customTimeLineWeek");
    } else {
        calendarApi.value.changeView("customGridWeek");
    }
    calendarApi.value.today();
    title.value = calendarApi.value.view.title;

}
// 天
function day() {
    calendarApi.value.today();
    title.value = calendarApi.value.view.title;
}


</script>
<style lang="less" scoped>
.fc {
    /* the calendar root */
   //max-width: 1100px;
    margin: 0 auto;
    background-color: #efefef;
}

.fc-toolbar {
    width: 100%;
    margin: 30px auto;
    display: flex;
    flex: 1;
    justify-content: space-around;
    align-content: center;
}

.fc-center {
    /* height: 40px; */
    display: flex;
    align-content: center;
    text-align: center;
}

.fc-center .title {
    font-size: 16px;
    padding: 0 15px;
    font-weight: 700;
    /* height: 40px; */
    /* line-height: 40px; */
}
</style>